package com.lxc.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxc.entity.BusinessException;
import com.lxc.entity.Chapters;
import com.lxc.mapper.ChapterMapper;
import com.lxc.service.ChapterService;
import com.lxc.service.config.RabbitMQConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapters> implements ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Chapters getByChapterId(Integer chapterid) {
//        log.info("{}",chapterMapper.selectByChapterId(chapterid));
        if (chapterid == null){
            throw new BusinessException(400,"章节id不能为空");
        }
        return chapterMapper.selectByChapterId(chapterid);
    }

    @Override
    public boolean deleteByChapterId(Integer chapterid) {
        if (chapterid != null){
            boolean i=chapterMapper.deleteById(chapterid) > 0;
            if (i){
                return true;
            }
            else{
                throw new BusinessException(500, "删除失败");
            }
        }
        return false;
    }

    @Override
    public boolean saveChapter(Chapters chapter) {
        if (chapter != null){
            boolean i=chapterMapper.insert(chapter) > 0;
            if (i){
                // 保存章节逻辑...
                Integer workId = chapter.getWorkId();

                // 构造消息内容（可为 workId 或 JSON）
                Message message = new Message(workId.toString().getBytes(), new MessageProperties());

                // 发送到 RabbitMQ
                rabbitTemplate.send(RabbitMQConfig.NOVEL_EXCHANGE, "novel.update", message);

                return true;
            }
            else{
                throw new BusinessException(500, "保存失败");
            }
        }
        return false;
    }

}